<!DOCTYPE html>
<html lang="zh-CN">
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <!-- CSRF Token -->
    <meta name="csrf-token" content="UHTlF87GUSX7Fc2i8l34xlCwzyt0c5HisHVRSaoi">
        <title>一篇搞定RSA加密与SHA签名|与Java完全同步 - CocoaChina_一站式开发者成长社区</title>
    
    <meta name="keywords"
      content="RSA加密,SHA签名" />
    <meta name="description"
      content="RSA是一种非对称加密算法，常用来对传输数据进行加密，配合上数字摘要算法，也可以进行文字签名。" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″ />
    <link rel="icon" href="https://jdi.cocosbcx.net/image/cocoachina/cocoachina.ico" type="image/x-icon">
    <!--收藏夹显示图标-->
    <link rel="shortcut icon" href="https://jdi.cocosbcx.net/image/cocoachina/cocoachina.ico" type="image/x-icon">
    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <!-- <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet"> -->
	<link href="http://www.cocoachina.com/css/gfamily.css" rel="stylesheet">
    <!-- Styles -->
    <link href="http://www.cocoachina.com/css/cocoachina.css?v=1.1.10" rel="stylesheet">

    <link href="http://www.cocoachina.com/css/baidu.search.css?v=1.1.8" rel="stylesheet">
    <link href="http://www.cocoachina.com/js/swiper/swiper.min.css?v=1.1.4" rel="stylesheet">
    <!-- <link href="http://www.cocoachina.com/css/reset.css?v=1.1.3" rel="stylesheet"> -->
    <link href="http://www.cocoachina.com/css/common.css?v=1.1.8" rel="stsylesheet">
	<link href="http://www.cocoachina.com/css/account.css?v=1.1.5" rel="stylesheet">
	<script src="http://www.cocoachina.com/js/jquery-3.3.1.min.js?v=1.0.0"></script>
	<script data-ad-client="ca-pub-5394824908356892" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
	<!-- <script  src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> -->
	<!-- <script src="http://www.cocoachina.com/js/namespace.js?v=1.0.1"></script> -->
    <script>
		var CC = {
	api: {}
}
		window.CC == {} ? CC = {} : CC = window.CC;
		$.extend(CC.api, {
			messageReadUrl: "http://www.cocoachina.com/account/message/read"
		})
    	window.messageReadUrl = "http://www.cocoachina.com/account/message/read";
    </script>



  

      <link rel="stylesheet" href="http://www.cocoachina.com/css/bootstrap.min.css?v=1.0.0">
    <link rel="stylesheet" href="http://www.cocoachina.com/css/detail.css?v=1.1.31">
    <style>
        .message{
            line-height: 54px !important;
        }
        /* 合master删除 */
        .input-box input{
            width: 100%;
            background: rgba(62,74,86,1);
            border: 0;
        }
        
    </style>
</head>

<body>
	<div id="app" class="">
		<div class="wrap">
			<div class="row">
<div class="col-md-12 hidden-sm hidden-xs">
    <header class="header">
        <div class="header" id="header">
            <div class="header-wrap">
                <ul class="header-left lt">
                    <li>
                        <a href="http://www.cocoachina.com" target="_self">
                            <img class="logo" src="https://jdi.cocosbcx.net/image/cocoachina/new_logo.png" alt>
                        </a>
                    </a></li>
                    <li>
                        <a href="http://www.cocoachina.com" target="_self">首页</a>
                    </a></li>
                    
                        
                    
                    <li>
                        <a href="http://www.cocoachina.com/bbs/" target="_blank">论坛</a>
                    </li>
                    <li>
                        <a href="http://code.cocoachina.com/" target="_blank">代码</a>
                    </li>
                    <li>
                        <a href="http://tools.cocoachina.com/" target="_blank">工具</a>
                    </li>
                    <!-- <li>
                        <a href="http://blog.cocoachina.com/" target="_blank">博客</a>
                    </li> -->
                    <li>
                        <a href="http://www.cocoachina.com/brochure/class" target="_blank">课堂</a>
                    </li>
                    
                        
                    
                </ul>
                <ul class="header-right rt">
                <div class="input-box">
                    <script type="text/javascript">
                        (function(){
                            document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));
                            // var bdcs = document.createElement('script');
                            // bdcs.type = 'text/javascript';
                            // bdcs.async = true;
                            // bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=3744990162378891678' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);
                            // var s = document.getElementsByTagName('script')[0];
                            // s.parentNode.insertBefore(bdcs, s);
                        })();
                    </script>
                </div>
                
                                    <div class="write-article">
                        <div class="art-btn"><a href="http://www.cocoachina.com/articles/new"><img src="http://www.cocoachina.com/images/store.png" alt="">写文章</a></div>
                    </div>
                    <div class="info">
                        <div class="register">
                            <a href="http://www.cocoachina.com/auth/register" target="_self">注册</a>
                        </div>
                        <i class="cut"></i>
                        <div class="login">
                            <a class="active" href="http://www.cocoachina.com/auth/login" target="_self">登录</a>
                        </div>
                    </div>
                                </ul>
            </div>
            <div class="concat">
                <div class="kefu">
                    官方<br />客服
                    <div class="ma"></div>
                </div>
                <div class="dingyuhao">
                    订阅号
                    <div class="ma"></div>
                </div>
                <a href="#header" class="top-btn" id="top_btn"></a>
            </div>
        </div>
    </header>
</div>
</div>
<!-- <script async src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> -->
<script async src="http://www.cocoachina.com/js/znsv.baidu.js"></script>
<script>
    if (location.pathname == '/') {
        $("#header .header-wrap").css({width: '1200px'})
    }
</script>
			<main class="main">
				    <div class="row">
    <div class="col-md-12">
        <div class="detail-content">
        <div class="bdsharebuttonbox share " data-tag="share_1" data="{'url':'http://yourname.domain.com/shareA.html'}">
            <div class="share-contents hidden-sm hidden-xs">
                                <span class="num vote-num" data-vote ="0">0</span>
                                <div class="icon vote">
                                            <img src="http://www.cocoachina.com/images/good_gray.png" data-src="http://www.cocoachina.com/images/c-good.png" alt="" class="">
                                    </div>
                
                <div class="icon collect">
                                            <img src="http://www.cocoachina.com/images/pre-star.png" data-src="http://www.cocoachina.com/images/c-star.png" alt="" class="">
                                    </div>
                <div class="icon">
                    <img  style="width:26px;height:auto" alt="" data-cmd="weixin" src="http://www.cocoachina.com/images/weixin-n.png" data-src="http://www.cocoachina.com/images/weixin-c.png">
                </div>
                <div class="icon qq " >
                    <img style="height:24px;height:auto;margin-top:12px" class="bds_sqq" data-cmd="sqq" src="http://www.cocoachina.com/images/qq-n.png" data-src="http://www.cocoachina.com/images/qq-c.png">
                </div>
                <div class="icon weibo " >
                    <img style="width:26px;height:auto" class="bds_tsina" data-cmd="tsina" src="http://www.cocoachina.com/images/weibo-n.png" data-src="http://www.cocoachina.com/images/weibo-c.png">
                </div>

            </div>

                

                
            </div>
            <div>
            <!-- class="lt" -->
                <!--  -->
                <div class="left">
                    <div class="articles">
                        <h3 class="cocoa-article-title">一篇搞定RSA加密与SHA签名|与Java完全同步</h3>
                        <div class="cocoa-auth-info">
                            <img class="hidden-sm hidden-xs" src="https://jdi.cocosbcx.net/image/cocoachina/user.png" alt="">
                            <span class="name">suiling</span><i>·</i>
                            <span class="time">2016-01-12</span>
                            <span class="read-num hidden-sm hidden-xs">阅读数 9146</span>
                            <!-- <i>·</i> -->
                                                    </div>

                                                <div class="details" id="details" data-id = "14940">
                            <p style="text-align:center"><img src="http://api.cocoachina.com/uploads/20160111/1452478838338149.jpg" title="1452478838338149.jpg" alt="wKioL1QfkDbCO8A6AAHa8IRz3J0002.jpg" width="544" height="386" style="width: 544px; height: 386px;"/></p><p>本文是投稿文章，作者：<a href="http://www.jianshu.com/p/a1bad1e2be55" target="_blank">Panda_iOS</a></p><p>看到这篇文章的同学可幸福了，当时在做RSA加密与签名的时候网上的资料简直不要太老，做完后实在是忍受不下去了，这篇文章我会详细讲解iOS如何实现RSA加密与签名，<span style="line-height: 1.8;">并且与Java完全同步，这是我的第二篇博客，若有什么不足之处还请大家指教。</span></p><p><span style="color: rgb(0, 176, 80);"><strong>基础知识</strong></span></p><p></p><p><strong>什么是RSA？</strong><br/>答：RSA是一种非对称加密算法，常用来对传输数据进行加密，配合上数字摘要算法，也可以进行文字签名。</p><p><strong>RSA加密中padding？</strong><br/>答：padding即填充方式，由于RSA加密算法中要加密的明文是要比模数小的，padding就是通过一些填充方式来限制明文的长度。后面会详细介绍padding的几种模式以及分段加密。</p><p><strong>加密和加签有什么区别？</strong><br/>答：加密：公钥放在客户端，并使用公钥对数据进行加密，服务端拿到数据后用私钥进行解密。<br/>加签：私钥放在客户端，并使用私钥对数据进行加签，服务端拿到数据后用公钥进行验签。<br/>前者完全为了加密；后者主要是为了防恶意攻击，防止别人模拟我们的客户端对我们的服务器进行攻击，导致服务器瘫痪。</p><p><span style="color: rgb(0, 176, 80);"><strong>基本原理</strong></span></p><p></p><p>RSA使用“密钥对”对数据进行加密解密，在加密解密前需要先生存公钥（Public Key）和私钥（Private Key）。<br/>公钥(Public key):&nbsp;用于加密数据. 用于公开, 一般存放在数据提供方, 例如iOS客户端。<br/>私钥(Private key):&nbsp;用于解密数据. 必须保密, 私钥泄露会造成安全问题。<br/>iOS中的Security.framework提供了对RSA算法的支持，这种方式需要对密匙对进行处理, 根据public key生成证书, 通过private key生成p12格式的密匙。想想jave直接用字符串进行加密解密简单多了。(⊙o⊙)…</p><p><span style="color: rgb(0, 176, 80);"><strong>实战</strong></span></p><p></p><p><strong>证书生成</strong></p><ul class=" list-paddingleft-2" style="list-style-type: disc;"><li><p>RSA加密这块公钥、私钥必不可少的。Apple是不支持直接使用字符串进行加密解密的，推荐使用p12文件。这边教大家去生成在加密中使用到的所有文件，并提供给Java使用，想当年这个公钥私钥搞了半天了。 %&gt;_&lt;%</p></li><li><p>生成模长为1024bit的私钥<br/>openssl genrsa -out private_key.pem 1024</p></li><li><p>生成certification require file<br/>openssl req -new -key private_key.pem -out rsaCertReq.csr</p></li><li><p>生成certification 并指定过期时间<br/>openssl x509 -req -days3650-in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt</p></li><li><p>生成公钥供iOS使用<br/>openssl x509 -outform der -in rsaCert.crt -out public_key.der</p></li><li><p>生成私钥供iOS使用 这边会让你输入密码，后期用到在生成secKeyRef的时候会用到这个密码<br/>openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt</p></li><li><p>生成pem结尾的公钥供Java使用<br/>openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout</p></li><li><p>生成pem结尾的私钥供Java使用openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt</p></li></ul><p>以上所有的步骤都是在终端下完成的哦 (^__^)</p><p><strong>生成公钥和私钥的secKeyRef</strong></p><p></p><pre class="brush:js;toolbar:false">//根据你的p12文件生成私钥对应的SecKeyRef&nbsp;这边返回若是nil&nbsp;请检查你p12文件的生成步骤
-&nbsp;(SecKeyRef)getPrivateKeyRefrenceFromData:(NSData*)p12Data&nbsp;password:(NSString*)password&nbsp;{

SecKeyRef&nbsp;privateKeyRef&nbsp;=&nbsp;NULL;
NSMutableDictionary&nbsp;*&nbsp;options&nbsp;=&nbsp;[[NSMutableDictionary&nbsp;alloc]&nbsp;init];
[options&nbsp;setObject:&nbsp;password&nbsp;forKey:(__bridge&nbsp;id)kSecImportExportPassphrase];
CFArrayRef&nbsp;items&nbsp;=&nbsp;CFArrayCreate(NULL,&nbsp;0,&nbsp;0,&nbsp;NULL);
OSStatus&nbsp;securityError&nbsp;=&nbsp;SecPKCS12Import((__bridge&nbsp;CFDataRef)&nbsp;p12Data,&nbsp;(__bridge&nbsp;CFDictionaryRef)options,&nbsp;&amp;items);
if&nbsp;(securityError&nbsp;==&nbsp;noErr&nbsp;&amp;&amp;&nbsp;CFArrayGetCount(items)&nbsp;&gt;&nbsp;0)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;CFDictionaryRef&nbsp;identityDict&nbsp;=&nbsp;CFArrayGetValueAtIndex(items,&nbsp;0);
&nbsp;&nbsp;&nbsp;&nbsp;SecIdentityRef&nbsp;identityApp&nbsp;=&nbsp;(SecIdentityRef)CFDictionaryGetValue(identityDict,&nbsp;kSecImportItemIdentity);
&nbsp;&nbsp;&nbsp;&nbsp;securityError&nbsp;=&nbsp;SecIdentityCopyPrivateKey(identityApp,&nbsp;&amp;privateKeyRef);
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(securityError&nbsp;!=&nbsp;noErr)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;privateKeyRef&nbsp;=&nbsp;NULL;
&nbsp;&nbsp;&nbsp;&nbsp;}
}
CFRelease(items);

return&nbsp;privateKeyRef;
}</pre><p>-</p><pre class="brush:js;toolbar:false">&nbsp;//根据你的der文件公钥对应的SecKeyRef
&nbsp;-&nbsp;(SecKeyRef)getPublicKeyRefrenceFromeData:&nbsp;&nbsp;&nbsp;&nbsp;(NSData*)derData&nbsp;{
&nbsp;
SecCertificateRef&nbsp;myCertificate&nbsp;=&nbsp;SecCertificateCreateWithData(kCFAllocatorDefault,&nbsp;(__bridge&nbsp;CFDataRef)derData);
SecPolicyRef&nbsp;myPolicy&nbsp;=&nbsp;SecPolicyCreateBasicX509();
SecTrustRef&nbsp;myTrust;
OSStatus&nbsp;status&nbsp;=&nbsp;SecTrustCreateWithCertificates(myCertificate,myPolicy,&amp;myTrust);
SecTrustResultType&nbsp;trustResult;
if&nbsp;(status&nbsp;==&nbsp;noErr)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;status&nbsp;=&nbsp;SecTrustEvaluate(myTrust,&nbsp;&amp;trustResult);
}
SecKeyRef&nbsp;securityKey&nbsp;=&nbsp;SecTrustCopyPublicKey(myTrust);
CFRelease(myCertificate);
CFRelease(myPolicy);
CFRelease(myTrust);

return&nbsp;securityKey;
}</pre><p><strong>加密与解密</strong></p><p></p><pre class="brush:js;toolbar:false">-&nbsp;(NSData*)rsaEncryptData:(NSData*)data&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;SecKeyRef&nbsp;key&nbsp;=&nbsp;[self&nbsp;getPublicKey];
&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;cipherBufferSize&nbsp;=&nbsp;SecKeyGetBlockSize(key);
&nbsp;&nbsp;&nbsp;&nbsp;uint8_t&nbsp;*cipherBuffer&nbsp;=&nbsp;malloc(cipherBufferSize&nbsp;*&nbsp;sizeof(uint8_t));
&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;blockSize&nbsp;=&nbsp;cipherBufferSize&nbsp;-&nbsp;11;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;blockCount&nbsp;=&nbsp;(size_t)ceil([data&nbsp;length]&nbsp;/&nbsp;(double)blockSize);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NSMutableData&nbsp;*encryptedData&nbsp;=&nbsp;[[NSMutableData&nbsp;alloc]&nbsp;init];
&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;i=0;&nbsp;i&lt;blockCount;&nbsp;i++)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;unsigned&nbsp;long&nbsp;bufferSize&nbsp;=&nbsp;MIN(blockSize&nbsp;,&nbsp;[data&nbsp;length]&nbsp;-&nbsp;i&nbsp;*&nbsp;blockSize);
&nbsp;&nbsp;&nbsp;&nbsp;NSData&nbsp;*buffer&nbsp;=&nbsp;[data&nbsp;subdataWithRange:NSMakeRange(i&nbsp;*&nbsp;blockSize,&nbsp;bufferSize)];
&nbsp;&nbsp;&nbsp;&nbsp;OSStatus&nbsp;status&nbsp;=&nbsp;SecKeyEncrypt(key,&nbsp;kSecPaddingPKCS1,&nbsp;(const&nbsp;uint8_t&nbsp;*)[buffer&nbsp;bytes],&nbsp;[buffer&nbsp;length],&nbsp;cipherBuffer,&nbsp;&amp;cipherBufferSize);
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(status&nbsp;!=&nbsp;noErr)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil;
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;NSData&nbsp;*encryptedBytes&nbsp;=&nbsp;[[NSData&nbsp;alloc]&nbsp;initWithBytes:(const&nbsp;void&nbsp;*)cipherBuffer&nbsp;length:cipherBufferSize];
&nbsp;&nbsp;&nbsp;&nbsp;[encryptedData&nbsp;appendData:encryptedBytes];
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;if&nbsp;(cipherBuffer){
&nbsp;&nbsp;&nbsp;&nbsp;free(cipherBuffer);
&nbsp;&nbsp;}
&nbsp;&nbsp;
&nbsp;&nbsp;return&nbsp;encryptedData;
&nbsp;&nbsp;}</pre><p><strong>-</strong></p><p></p><pre class="brush:js;toolbar:false">-&nbsp;(NSData*)rsaDecryptData:(NSData*)data&nbsp;{
SecKeyRef&nbsp;key&nbsp;=&nbsp;[self&nbsp;getPrivatKey];

size_t&nbsp;cipherBufferSize&nbsp;=&nbsp;SecKeyGetBlockSize(key);
size_t&nbsp;blockSize&nbsp;=&nbsp;cipherBufferSize;
size_t&nbsp;blockCount&nbsp;=&nbsp;(size_t)ceil([data&nbsp;length]&nbsp;/&nbsp;(double)blockSize);

NSMutableData&nbsp;*decryptedData&nbsp;=&nbsp;[[NSMutableData&nbsp;alloc]&nbsp;init];

for&nbsp;(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;&lt;&nbsp;blockCount;&nbsp;i++)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;unsigned&nbsp;long&nbsp;bufferSize&nbsp;=&nbsp;MIN(blockSize&nbsp;,&nbsp;[data&nbsp;length]&nbsp;-&nbsp;i&nbsp;*&nbsp;blockSize);
&nbsp;&nbsp;&nbsp;&nbsp;NSData&nbsp;*buffer&nbsp;=&nbsp;[data&nbsp;subdataWithRange:NSMakeRange(i&nbsp;*&nbsp;blockSize,&nbsp;bufferSize)];
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;cipherLen&nbsp;=&nbsp;[buffer&nbsp;length];
&nbsp;&nbsp;&nbsp;&nbsp;void&nbsp;*cipher&nbsp;=&nbsp;malloc(cipherLen);
&nbsp;&nbsp;&nbsp;&nbsp;[buffer&nbsp;getBytes:cipher&nbsp;length:cipherLen];
&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;plainLen&nbsp;=&nbsp;SecKeyGetBlockSize(key);
&nbsp;&nbsp;&nbsp;&nbsp;void&nbsp;*plain&nbsp;=&nbsp;malloc(plainLen);
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;OSStatus&nbsp;status&nbsp;=&nbsp;SecKeyDecrypt(key,&nbsp;kSecPaddingPKCS1,&nbsp;cipher,&nbsp;cipherLen,&nbsp;plain,&nbsp;&amp;plainLen);
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(status&nbsp;!=&nbsp;noErr)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil;
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;NSData&nbsp;*decryptedBytes&nbsp;=&nbsp;[[NSData&nbsp;alloc]&nbsp;initWithBytes:(const&nbsp;void&nbsp;*)plain&nbsp;length:plainLen];
&nbsp;&nbsp;&nbsp;&nbsp;[decryptedData&nbsp;appendData:decryptedBytes];
}

return&nbsp;decryptedData;
}</pre><p></p><p><strong>RSA加密中的Padding</strong></p><p></p><ul class=" list-paddingleft-2" style="list-style-type: disc;"><li><p>RSA_PKCS1_PADDING 填充模式，最常用的模式<br/>要求: 输入：必须 比 RSA 钥模长(modulus) 短至少11个字节, 也就是　RSA_size(rsa) – 11 如果输入的明文过长，必须切割，然后填充。<br/>输出：和modulus一样长<br/>根据这个要求，对于1024bit的密钥，block length = 1024/8 – 11 = 117 字节</p></li><li><p>RSA_PKCS1_OAEP_PADDING<br/>输入：RSA_size(rsa) – 41<br/>输出：和modulus一样长</p></li><li><p>RSA_NO_PADDING　　不填充<br/>输入：可以和RSA钥模长一样长，如果输入的明文过长，必须切割，　然后填充<br/>输出：和modulus一样长</p></li></ul><p><strong>签名与验证</strong></p><p></p><pre class="brush:js;toolbar:false">//对数据进行sha256签名
&nbsp;&nbsp;-&nbsp;(NSData&nbsp;*)rsaSHA256SignData:(NSData&nbsp;*)plainData&nbsp;{
&nbsp;&nbsp;SecKeyRef&nbsp;key&nbsp;=&nbsp;[self&nbsp;getPrivatKey];
&nbsp;&nbsp;size_t&nbsp;signedHashBytesSize&nbsp;=&nbsp;SecKeyGetBlockSize(key);
&nbsp;&nbsp;uint8_t*&nbsp;signedHashBytes&nbsp;=&nbsp;malloc(signedHashBytesSize);
&nbsp;&nbsp;memset(signedHashBytes,&nbsp;0x0,&nbsp;signedHashBytesSize);
&nbsp;&nbsp;size_t&nbsp;hashBytesSize&nbsp;=&nbsp;CC_SHA256_DIGEST_LENGTH;
&nbsp;&nbsp;uint8_t*&nbsp;hashBytes&nbsp;=&nbsp;malloc(hashBytesSize);
&nbsp;&nbsp;if&nbsp;(!CC_SHA256([plainData&nbsp;bytes],&nbsp;(CC_LONG)[plainData&nbsp;length],&nbsp;hashBytes))&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;nil;
}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SecKeyRawSign(key,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;kSecPaddingPKCS1SHA256,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hashBytes,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hashBytesSize,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;signedHashBytes,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&amp;signedHashBytesSize);
&nbsp;&nbsp;&nbsp;&nbsp;NSData*&nbsp;signedHash&nbsp;=&nbsp;[NSData&nbsp;dataWithBytes:signedHashBytes
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;length:(NSUInteger)signedHashBytesSize];
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(hashBytes)
&nbsp;&nbsp;&nbsp;&nbsp;free(hashBytes);
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(signedHashBytes)
&nbsp;&nbsp;&nbsp;&nbsp;free(signedHashBytes);
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;signedHash;
&nbsp;&nbsp;&nbsp;&nbsp;}</pre><p>-</p><pre class="brush:js;toolbar:false">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//这边对签名的数据进行验证&nbsp;验签成功，则返回YES
&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;(BOOL)rsaSHA256VerifyData:(NSData&nbsp;*)plainData&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;withSignature:(NSData&nbsp;*)signature&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;SecKeyRef&nbsp;key&nbsp;=&nbsp;[self&nbsp;getPublicKey];
&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;signedHashBytesSize&nbsp;=&nbsp;SecKeyGetBlockSize(key);
&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;void*&nbsp;signedHashBytes&nbsp;=&nbsp;[signature&nbsp;bytes];
&nbsp;&nbsp;&nbsp;&nbsp;size_t&nbsp;hashBytesSize&nbsp;=&nbsp;CC_SHA256_DIGEST_LENGTH;
&nbsp;&nbsp;&nbsp;&nbsp;uint8_t*&nbsp;hashBytes&nbsp;=&nbsp;malloc(hashBytesSize);
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!CC_SHA256([plainData&nbsp;bytes],&nbsp;(CC_LONG)[plainData&nbsp;length],&nbsp;hashBytes))&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;NO;
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;OSStatus&nbsp;status&nbsp;=&nbsp;SecKeyRawVerify(key,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;kSecPaddingPKCS1SHA256,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hashBytes,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hashBytesSize,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;signedHashBytes,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;signedHashBytesSize);
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;status&nbsp;==&nbsp;errSecSuccess;
&nbsp;&nbsp;&nbsp;&nbsp;}</pre><p>文章到此就结束了，希望这篇文章对大家有所帮助。想看demo的请点击：<a href="https://github.com/panxianyue/RSACryptor.git" target="_blank">XYRSACryptor</a></p>
                        </div>
                    </div>
                </div>

            </div>
            <div class="right rt hidden-sm hidden-xs">
                <div class="atticle-wrap">
                                        <div class="reyi hidden-sm hidden-xs" style="display: none"><style>
    .ul{
        padding: 0;
    }
    h3{
        margin: 0;
    }
.right .atticle-wrap{
    width:280px;
    height:344px;
}
.right .atticle-wrap .hot-article {
    margin-bottom: 18px !important;
    background:rgba(255,255,255,1) !important;
    box-shadow: 0px 0px 6px 0px rgba(238,238,238,1);
}
.right .atticle-wrap .hot-article .top-til{
    height:50px;
    line-height: 50px;
    border-bottom:1px silid #EBEBEB;
    padding-left:14px;
    font-size:18px;
    font-family:PingFangSC-Semibold,PingFang SC;
    font-weight:600;
}
.right .atticle-wrap .title-wrap{
    height: 50px;
    border-bottom: 1px solid rgba(235,235,235,1);
    padding: 0 14px;
}
.right .atticle-wrap .title-wrap h3 .title{
    font-size:18px;
    font-family: PingFangSC-Regular, sans-serif;
    font-weight:600;
    color:rgba(42,42,42,1);
    line-height:50px;
}
.right .atticle-wrap .title-wrap h3 .rt .title-btn{
    font-size:14px;
    font-family: PingFangSC-Regular, sans-serif;
    font-weight:400
    color:rgba(102,102,102,1);
    line-height:50px;
    cursor: pointer;
}
.right .atticle-wrap .title-wrap h3 .rt .title-btn.active{
    color:rgba(82,192,246,1);
}

.right .rt {
    display: flex;
    align-items: center;
}

.right .rt .cut {
    display: flex;
    height: 10px;
    width: 1px;
    background: #9b9b9b;
    margin: 0 6px
}
.right .atticle-wrap .month,
.right .atticle-wrap .week{
    padding: 0 14px;
}
.right .atticle-wrap .month li,
.right .atticle-wrap .week li{
    height: 54px;
    border-bottom: 1px dashed rgba(235,235,235,1);
    padding: 18px 0; 
}
.right .atticle-wrap .month li:last-child,
.right .atticle-wrap .week li:last-child{
    border: 0; 
}
.right .atticle-wrap .month li .num,
.right .atticle-wrap .week li .num{
    width:18px;
    height:18px;
    line-height: 18px;
    text-align: center;
    background:rgba(45,53,61,1);
    display: inline-block;
    color: #fff;
    float: left;
}
.right .atticle-wrap .month li .items,
.right .atticle-wrap .week li .items{
    float: left;
    margin-left: 14px;
    line-height: 17px;
    width: calc(100% - 32px);
}
.right .atticle-wrap .month li .items p,
.right .atticle-wrap .week li .items p{
    width: 100%;
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.right .atticle-wrap .month li .items a,
.right .atticle-wrap .week li .items a{
    font-size:14px;
    font-family: PingFangSC-Regular, sans-serif;
    font-weight:400;
    color:rgba(42,42,42,1);
}
</style>

<div class="right rt">

    <div class="atticle-wrap">
        
        <ul class="hot-article">
            <div class="title-wrap">
                <h3>
                    <span class="title">论坛热帖</span>
                    <div class="rt">
                                <span class="title-btn article-type active"
                                      onclick="onChangeHotArticleType('week_hot_bbs')" id="week_hot_bbs">本周最热</span>
                        <i class="cut"></i>
                        <span class="title-btn article-type" onclick="onChangeHotArticleType('month_hot_bbs')" id="month_hot_bbs">本月最热</span>
                    </div>
                </h3>
            </div>
            <div class="week week_hot_bbs" style="display: block;">
                            </div>
            <div class="month month_hot_bbs" style="display: none;">
                                    <li>
                        <span class="num">1</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/bbs/read.php?tid-1796052.html" target="_blank">
                                <p class="item-title">萌新入门iOS提问</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">2</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/bbs/read.php?tid-1796055.html" target="_blank">
                                <p class="item-title">十年了为了跳槽还在刷题</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">3</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/bbs/read.php?tid-1796054.html" target="_blank">
                                <p class="item-title">招聘：跪求简历，IOS开发（可远程工作、兼职），10-20K</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">4</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/bbs/read.php?tid-1796056.html" target="_blank">
                                <p class="item-title">模拟器只能在release下运行</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">5</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/bbs/read.php?tid-1796049.html" target="_blank">
                                <p class="item-title">各位大佬，蓝牙怎么设置不用配对就可以连接</p>
                            </a>
                        </div>
                    </li>
                            </div>
        </ul>
        <ul class="hot-article">
            <div class="title-wrap">
                <h3>
                    <span class="title">热门文章</span>
                    <div class="rt">
                        <span class="title-btn article-type active"
                                onclick="onChangeHotArticleType('week_hot')" id="week_hot">本周最热</span>
                                <i class="cut"></i>
                        <span class="title-btn article-type" onclick="onChangeHotArticleType('month_hot')" id="month_hot">本月最热</span>
                    </div>
                </h3>
            </div>
            <div class="week week_hot" style="display: block;">
                                    <li>
                        <span class="num">1</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903417">
                                <p class="item-title">2021款iPad Pro准备就绪：苹果最快下周二发布</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">2</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903399">
                                <p class="item-title">库克谈苹果应用商店佣金高：对开发者一视同仁</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">3</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903451">
                                <p class="item-title">顺丰巨亏，极兔、百世被罚，快递行业出了什么问题？</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">4</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903474">
                                <p class="item-title">一部iPhone 11 Pro的logo罕见错位 并以1万7的价格售出</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">5</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903469">
                                <p class="item-title">iPhone最新概念图曝光：背部副屏引人注目</p>
                            </a>
                        </div>
                    </li>
                            </div>
            <div class="month month_hot" style="display: none;">
                                    <li>
                        <span class="num">1</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903204">
                                <p class="item-title">iOS微信8.0.3内测更新：支付页面改版等5大变化</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">2</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903244">
                                <p class="item-title">简单三步，让 iPhone 自带日历 App 显示国家节假日安排</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">3</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903371">
                                <p class="item-title">iOS 14.5强制要求App提示用户许可权限</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">4</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903337">
                                <p class="item-title">华为鸿蒙OS与安卓、iOS有什么区别？</p>
                            </a>
                        </div>
                    </li>
                                    <li>
                        <span class="num">5</span>
                        <div class="items">
                            <a href="http://www.cocoachina.com/articles/903387">
                                <p class="item-title">iOS 14.5正式版将上线：苹果提醒所有开发者执行新政</p>
                            </a>
                        </div>
                    </li>
                            </div>
        </ul>
        <ul class="contact-us">
            <div class="side-friend">
                <ul class="qrcode">
                    <li>
                        <img src="http://www.cocoachina.com/images/qrcode/cocoschina.png" alt="">
                        <p>Cocoa社区</p>
                    </li>
                    <li>
                        <img src="http://www.cocoachina.com/images/qrcode/official_account.png" alt="">   
                        <p>区块链社区</p>
                    </li>
                </ul>
                <p>
                    <a href="http://www.cocoachina.com/aboutus/agrement/index.html" target="_blank">用户协议</a>
                    ·
                    <a href="http://www.cocoachina.com/aboutus/yinsi/index.html" target="_blank">隐私协议</a>
                    ·
                    <a href="http://www.cocoachina.com/aboutus/quanli/index.html" target="_blank">权利声明</a>
                    ·
                    <a href="http://www.cocoachina.com/aboutus/index.html" target="_blank">商务合作</a>
                </p>
                <p>
                    <a href="https://beian.miit.gov.cn" target="_blank">京ICP备 11006519号-1  京ICP证 100954号</a>
                </p>
                <p>
                    <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010502037140" target="_blank">京公安网备 1101502037140号</a>
                </p>
                <p>
                    <a href="http://182.131.21.137/ccnt-apply/admin/business/preview/business-preview!lookUrlRFID.action?main_id=A580B24B1AE846CE9DA949026D63939F" target="_blank">京网文[2018]6281-491号</a></p>
                <p>
                    <a href="http://www.chukong-inc.com/" target="_blank">北京触控科技有限公司</a>
                </p>
                <p>
                    <a href="javascript:void(0)" target="_blank">版权所有@2020  Chukong Technologes,Inc</a>
                </p>
                <p>
                    <a href="http://www.cocoachina.com/corps" target="_blank">友情链接</a>
                </p>
            </div>
        </ul>



        
            
                    
                    
                    
                
            
            
                    
                    
                    
                

            
            
                    
                    
                    
                
            
            
                    
                    
                
            
            
                    
                    
                    
                
            
            
                    
                    
                    
                
            
        
    </div>
</div>
</div>
                    <div>

                        <div id="directory">
                            <div class="directorys"></div>
                        </div>

                    <div class="side-friend" id="side-friend-qrcode">
                            <ul class="qrcode">
                                <li>
                                    <img src="http://www.cocoachina.com/images/qrcode/cocoschina.png" alt="">
                                    <p>Cocoa社区</p>
                                </li>
                                <li>
                                    <img src="http://www.cocoachina.com/images/qrcode/official_account.png" alt="">   
                                    <p>区块链社区</p>
                                </li>
                            </ul>
                            <p>
                                <a href="http://www.cocoachina.com/aboutus/agrement/index.html" target="_blank">用户协议</a>
                                ·
                                <a href="http://www.cocoachina.com/aboutus/yinsi/index.html" target="_blank">隐私协议</a>
                                ·
                                <a href="http://www.cocoachina.com/aboutus/quanli/index.html" target="_blank">权利声明</a>
                                ·
                                <a href="http://www.cocoachina.com/aboutus/index.html" target="_blank">商务合作</a>
                            </p>
                            <p>
                                <a href="http://www.miibeian.gov.cn/" target="_blank">京ICP备 1006519号  京ICP证 100954号</a>
                            </p>
                            <p>
                                <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010502037140" target="_blank">京公安网备 1101502037140号</a>
                            </p>
                            <p>
                                <a href="http://182.131.21.137/ccnt-apply/admin/business/preview/business-preview!lookUrlRFID.action?main_id=A580B24B1AE846CE9DA949026D63939F" target="_blank">京网文[2018]6281-491号</a></p>
                            <p>
                                <a href="http://www.chukong-inc.com/" target="_blank">北京触控科技有限公司</a>
                            </p>
                            <p>
                                <a href="javascript:void(0)" target="_blank">版权所有@2020  Chikong Technologes,Inc</a>
                            </p>
                            <p>
                                <a href="http://www.cocoachina.com/corps" target="_blank">友情链接</a>
                            </p>
                        </div>
                    </div>

                </div>
            </div> 
            
        </div>
    </div>
    </div>
    <div class="drawer"></div>
    <div class="login-main">
        <div class="login-contain">
          <p>温馨提示</p>
          <p>登录后才可以操作哦，<a href="http://www.cocoachina.com/auth/login" target="_self">去登录</a></p>
        </div>
        <div class="close">×</div>  
    </div>
    <div class="success" style="display: none"><span>复制成功</span></div>
			</main>
			<div class="cover-content"></div>
		</div>
	</div>

	<!-- Scripts -->

	<!-- <script src="http://www.cocoachina.com/js/jquery-3.3.1.min.js?v=1.0.0"></script> -->
	<script src="http://www.cocoachina.com/js/swiper/swiper.min.js?v=1.0.0"></script>
	<script src="http://www.cocoachina.com/js/index.js?v=1.1.2" defer></script>
	<style>
.flashy {
    font-family: Arial, sans-serif;
    padding: 11px 30px;
    border-radius: 4px;
    font-weight: 400;
    position: fixed;
    bottom: 20px;
    right: 20px;
    font-size: 16px;
    color: #fff;
}

.flashy--success {
    background-color: #99c93d;
    color: #fff;
}

.flashy--warning {
    color: #8a6d3b;
    background-color: #fcf8e3;
    border-color: #faebcc;
}

.flashy--muted {
    background: #eee;
    color: #3a3a3a;
    border: 1px solid #e2e2e2;
}

.flashy--muted-dark {
    background: #133259;
    color: #e2e1e7;
}

.flashy--info a,
.flashy--primary-dark a {
    color: #fff;
}

.flashy--error {
    background: #d14130;
    color: #fff;
}

.flashy--primary {
    background: #573e81;
}

.flashy--primary-dark {
    background: linear-gradient(to right, #133259 30%, #0d233e);
}

.flashy--info {
    background: #00baf3;
}

.flashy > ul {
    padding-left: 15px;
}

.flashy > p:only-of-type {
    margin-bottom: 0;
}

.flashy i {
    margin-right: 8px;
    position: relative;
    top: 6px;
}

.flashy .flashy__body {
    color: inherit;
}

@media  only screen and (max-width:1050px) {
    .flashy {
        text-align: center;
        right: 0;
        left: 50%;
        width: 300px;
        margin-left: -150px;
    }
}
</style>

<script>
    function flashy(message, link) {
        var template = $($("#flashy-template").html());
        $(".flashy").remove();
        template.find(".flashy__body").html(message).attr("href", link || "#").end()
         .appendTo("body").hide().fadeIn(300).delay(2800).animate({
            marginRight: "-100%"
        }, 300, "swing", function() {
            $(this).remove();
        });
    }
</script>


	<!-- Global site tag (gtag.js) - Google Analytics -->
  	    <script>
        // 黑名单字符串（MD5加密，16位大写）暂时只有两个;
		var black_str = "6d44eab61dcf5b1f0e6fa8f6595ee1bc,f27a70fef65ab50236291e1635e268f3";
		black_str = black_str.split(',')
		
    </script>
    <!-- <script async src="https://www.googletagmanager.com/gtag/js?id=UA-68950821-1"></script> -->
    <script>
        var MD5 = function(d){result = M(V(Y(X(d),8*d.length)));return result.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}
        var user_id = "0";
		if (black_str.indexOf(MD5(navigator.userAgent)) == -1) {
			window.dataLayer = window.dataLayer || [];
			function gtag(){dataLayer.push(arguments);}
			gtag('js', new Date());
			gtag('config', 'UA-68950821-1', {
				'user_id': user_id
			});
		}
		
        // window.dataLayer = window.dataLayer || [];
        // function gtag(){dataLayer.push(arguments);}
        // gtag('js', new Date());
        // gtag('config', 'UA-68950821-1', {
        //     'user_id': user_id
        // });

    </script>

    <!-- 浏览器访问文章数据源统计 add by XiaHB 2019/09/02 Begin; -->
    <script type="text/javascript">
        // 获取用户id,自动声明为全局变量;
        var user_id = "0";
        document.write(unescape("%3Cscript src='http://test-cocoachina.cocosbcx.net/statistics/res/js/statnew.js?v=2.0' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <!-- 浏览器访问文章数据源统计 add by XiaHB 2019/09/02   End; -->

    

	<script>

		$('.info').mousemove(function () {
			$(this).find('.photo').css({'border': '1px solid #52C0F6'})
			if ($(this).find('.info-center').is(':animated') == false) {
				$(this).find('.info-center').slideDown('normal');
				if ($('.info-detail').length) {
					$(this).height(206);
				}
			}
		});
		$('.info').mouseleave(function () {
			$(this).find('.photo').css({'border': '1px solid #2d353d'})
			$(this).find('.info-center').slideUp('normal');
			$(this).height(34);
		});
		$('.message').mousemove(function () {
			$(this).find('.infos img').attr('src', 'http://www.cocoachina.com/images/infos.png')
			if ($(this).find('.mes-center').is(':animated') == false) {
				$(this).find('.mes-center').slideDown('fast');
				if ($('.info-detail').length) {
					$(this).height(62);
				}
			}
		});
		$('.message').mouseleave(function () {
			$(this).find('.infos img').attr('src', 'http://www.cocoachina.com/images/c_infos.png')
			$(this).find('.mes-center').slideUp('fast');
			$(this).height(62);
		});

	</script>
	<script>
		var _hmt = _hmt || [];
		(function () {
			var hm = document.createElement("script");
			hm.src = "https://hm.baidu.com/hm.js?88399e4c4cf744609c4fc8c3a8935691";
			var s = document.getElementsByTagName("script")[0];
			s.parentNode.insertBefore(hm, s);
		})();
	</script>
	<script>
		(function(){
			var bp = document.createElement('script');
			var curProtocol = window.location.protocol.split(':')[0];
			if (curProtocol === 'https') {
				bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
			} else {
				bp.src = 'http://push.zhanzhang.baidu.com/push.js';
			}
			var s = document.getElementsByTagName("script")[0];
			s.parentNode.insertBefore(bp, s);
		})();
	</script>
	<script async src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="http://www.cocoachina.com/js/clipboard.js"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
    var id =  $("#details").attr('data-id');
    $.ajax({
        type: 'GET',
        url: "http://www.cocoachina.com/weixin/token",
        data: {
            'page_url': window.location.href,
            'id' : id,
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        dataType: "json",
        success: function(result) {
            if (result.error != 'ok'){
                return
            }
            var res = result.result;
            var desc = $('#details').text().substring(0, 200).trim();
            wx.config({
                debug: false, 
                appId: 'wx8022d6ceb147f93f',
                timestamp: res.timestamp,
                nonceStr: res.noncestr,
                signature: res.signature,
                jsApiList: [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage'
                ]
            });
            wx.ready(function () {
                var shareData = {
                    title: $('.cocoa-article-title').html() + '-CocoaChina',	//	标题
                    desc: desc,	//	描述
                    link: window.location.href,//	分享的URL，必须和当前打开的网页的URL是一样的
                    imgUrl: $("#details img").eq(0).attr('src')	//	缩略图地址
                };
                wx.onMenuShareAppMessage(shareData);
                wx.onMenuShareTimeline(shareData);
            });
            wx.error(function (res) {
            //alert(res.errMsg);//错误提示
            });
        }
    })

    var aid = "14940";
    var uid = "0";
    // 点赞、收藏用户交互
    $('.share-contents').on('mouseover', '.icon', function() {
        if ($(this).find('img').attr('click') != 1) {
            var dataSrc = $(this).find('img').attr('data-src');
            var Src = $(this).find('img').attr('src');
            $(this).find('img').attr('src', dataSrc)
            $(this).find('img').attr('data-src', Src)
        }
    })
    $('.share-contents').on('mouseout', '.icon', function() {
        if ($(this).find('img').attr('click') != 1) {
            var dataSrc = $(this).find('img').attr('data-src');
            var Src = $(this).find('img').attr('src');
            $(this).find('img').attr('src', dataSrc);
            $(this).find('img').attr('data-src', Src);
        }
    })
    // 点赞
    $('.vote').click(function () {
        if (uid == 0){
            $('.drawer, .login-main').attr('style','display: block;');
            return ;
        }
        $.ajax({
            type: 'POST',
            url: "http://www.cocoachina.com/articles/vote",
            data: {
                "aid":aid
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            dataType: "json",
            async: false,
            success: function (resp) {
                if (resp.code == 1){
                    $('.vote img').attr("src",'http://www.cocoachina.com/images/c-good.png');
                    $('.vote img').attr("click", 1);
                    $('.vote-num').addClass('active');
                    var voted = $('.vote-num').attr("data-vote");
                    var votes = parseInt(voted) + 1;
                    $('.vote-num').attr("data-vote",votes);
                    $('.vote-num').text(votes)
                }else if (resp.code == 2){
                    $('.vote img').attr("src",'http://www.cocoachina.com/images/good_gray.png');
                    $('.vote-num').removeClass('active');
                    var voted = $('.vote-num').attr("data-vote");
                    var votes = voted - 1;
                    $('.vote-num').attr("data-vote",votes);
                    $('.vote-num').text(votes)
                }
            },

        });
    })

    // 收藏
    $('.collect').click(function () {
        if (uid == 0){
            $('.drawer, .login-main').attr('style','display: block;');
            return ;
        }

        $.ajax({
            type: 'POST',
            url: "http://www.cocoachina.com/articles/star",
            data: {
                "aid":aid
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            dataType: "json",
            async: false,
            success: function (resp) {
                if (resp.code == 1){
                    console.log($(this))
                    $('.collect img').attr("src","http://www.cocoachina.com/images/c-star.png");
                    $('.collect img').attr('click', 1)
                }else if (resp.code == 2){
                    $('.collect img').attr("src",'http://www.cocoachina.com/images/pre-star.png');
                }
            },

        });

    })

    // 关闭弹框
    $('.close').click(function () {
      	$('.drawer, .login-main').attr('style', 'none');
    })

    
</script>
<script>
    $(function(){
        // 兼容编辑器 -start
        for (var i = 0; i < $('pre').length; i++) {
                    if ($('pre')[i].childNodes[0].localName !== 'code') {
                        $('pre').eq(i).html('<code>'+$('pre').eq(i).text()+'</code>')
                        $('pre').eq(i).append('<span class="copy-code-btn">复制代码</span>')
                    }
                }
                if ($('pre').find('.copy-code-btn').length <= 0) {
                    $('pre').append('<span class="copy-code-btn">复制代码</span>')
                } else if ($('code').find('.copy-code-btn').length > 0) {
                    $('code').find('.copy-code-btn').remove()
                    $('pre').append('<span class="copy-code-btn">复制代码</span>')
                }
                $('.copy-code-btn').css({
                    'position': 'absolute',
                    'top': '4px',
                    'right': '4px',
                    'font-size': '12px',
                    'color': '#4d4d4d',
                    'background-color': 'white',
                    'padding': '2px 8px',
                    'margin': '8px',

                    'border-radius': '4px',
                    'cursor': 'pointer',
                    'box-shadow': '0 2px 4px rgba(0,0,0,0.05), 0 2px 4px rgba(0,0,0,0.05)'
                })
                // 兼容编辑器 -end

                // 复制插件
                var clipboard;
                $('.copy-code-btn').each(function (index, ele) {
                    clipboard = new ClipboardJS(this, {
                        target: function () {
                        return $(ele).prev('code')[0]
                        }
                    })
                    clipboard.on('success', function(e) {
                        $('.success').fadeIn()
                        draftTimer = setTimeout(function () {
                            $('.success').fadeOut()
                        }, 1500)
                    });

                    clipboard.on('error', function(e) {
                        console.log(e);
                    });
                })

                // 图片懒加载  - 页面加载完成视口图片加载
                start();
            })
   

    // 去掉文章详情header标签的行内样式
    // $('#details h1, #details h2, #details h3, #details h4, #details h5').removeAttr('style')
     
    // 目录 -start
    var Nodes = $('#details h1, #details h2, #details h3, #details h4, #details h5');
    if ($('#details h1, #details h2').length > 0) {
        Nodes = $('#details h1, #details h2, #details h3');
    }

    if (Nodes.length < 1) {
        $('#directory').attr('style', 'display: none;');
        $('#side-friend-qrcode').attr('style', 'display: none;');
        $('.reyi').attr('style', 'display: block;');
    }
    var div = '<div class="cut"></div><div class="directory">目录</div>';
    for (var i = 0; i < Nodes.length; i++) {
        var header = document.createElement(Nodes[i].tagName);
        header.innerHTML = Nodes[i].innerText;
        Nodes[i] = header;

        if (Nodes[i].childNodes.length > 0) {
            if (Nodes[i].childNodes[0].localName == 'span') {
                Nodes[i].innerHTML = Nodes[i].innerText
            } else if (Nodes[i].childNodes[0].localName == 'a') {
                Nodes[i].innerHTML = Nodes[i].innerText
            } else if (Nodes[i].childNodes[0].localName == 'code') {
                Nodes[i].innerHTML = Nodes[i].innerText
            }
        }
        
        var header1 = document.createElement('h1');
        var header2 = document.createElement('h2');
        var header3 = document.createElement('h3');
        if ($('#details h1').length <= 0 && $('#details h2').length <= 0) {
            if (Nodes[i].tagName == 'H3') {
                header1.innerHTML = Nodes[i].innerText;
                Nodes.splice(i,1,header1)
            }
            if (Nodes[i].tagName == 'H4') {
                header2.innerHTML = Nodes[i].innerText;
                Nodes.splice(i,1,header2)
            }
            if (Nodes[i].tagName == 'H5') {
                header3.innerHTML = Nodes[i].innerText;
                Nodes.splice(i,1,header3)
            }
        }
        var $div = '<span class="dot"></span>';
        $($div).appendTo(Nodes[i]);
        let nodes;
        let hrefs;
        nodes = document.createElement('a');
        nodes.href = "#cocoachina" + i;
        Nodes[i].appendChild(nodes);
        $('#details h1, #details h2, #details h3, #details h4, #details h5').eq(i).attr("id", 'cocoachina' + i)

        $(Nodes[i]).addClass("nodes");
        div = div + Nodes[i].outerHTML;
    }
    $('#directory .directorys').html(div);
    // $('#side-friend-qrcode').attr('style', 'display: block;');
    // 目录 -end
    
    // 当页面开始滚动的时候，遍历图片，如果图片出现在视窗中，就加载图片
    var clock; //函数节流
    $(window).on('scroll',function(){
        if(clock){
            clearTimeout(clock);
        }
        clock = setTimeout(function(){
            start()
        },200)
    })

    function start(){
        $('#details img').not('[data-isLoading]').each(function () {
            if (isShow($(this))) {
                loadImg($(this));
            }
        })
    }

    // 判断图片是否出现在视窗的函数
    function isShow($node){
        return $node.offset().top <= $(window).height()+$(window).scrollTop();
    }

    // 加载图片的函数，就是把自定义属性data-src 存储的真正的图片地址，赋值给src
    function loadImg($img){
        $img.attr('src', $img.attr('data-src'));
        // 已经加载的图片，标识属性值为1
        $img.attr('data-isLoading',1);
    }


    var clickflag = false;
    var offsetHs = [0];
    var navs = '';
    init();

    $(document).scroll(function () {
        var top = document.body.scrollTop || document.documentElement.scrollTop;
        // console.log(top)
        // if (top > 300) {
        //     $('#directory').css({'position':'fixed','top': '10px'});
        // } else {
        //     $('#directory').css('position', 'static');
        // }
        debounce(isLightAnchor(top - document.documentElement.clientHeight))
        clickflag = false
    });
    $('#directory a').click(function () {
        clickflag = true;
        $(this).parent(".nodes").addClass('cur-anchor');
        $(this).parent(".nodes").siblings().removeClass('cur-anchor');
        // clickflag = false;
        return
    });
        

    function debounce(fn, delay = 200) {
        let timer;
        return function () {
        var context = this
        var args = arguments
        clearTimeout(timer)
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
        }
    }

    function init() {
        // $('#no').remove();
        // $('a[href=#no]').remove();
        navs = $('#directory a');
        handleOffsetValue();
    }

    function handleOffsetValue() {
        for (var i = 0; i < navs.length; i++) {
            var divID = $(navs[i]).attr('href');
            if (divID !== "javascript:void(0)") {
                offsetHs.push($(divID).offset().top + $(divID).get(0).offsetHeight * 0.8);
            }
        }
    }

    function isLightAnchor(scrollTop) {
        navs = $('#directory a');
        handleOffsetValue()
        for (var i = 0; i < navs.length; i++) {
            if (scrollTop >= offsetHs[i] && scrollTop < offsetHs[i + 1]) {
                if (!clickflag) {
                    $($('#directory a')[i]).parent(".nodes").addClass('cur-anchor')
                    $($('#directory a')[i]).parent(".nodes").siblings().removeClass('cur-anchor');
                }
            }
        }
        if (scrollTop == $('.detail-content').get(0).offsetHeight - $('#directory').height()) {
            $($('#directory a')[navs.length - 1]).parent(".nodes").addClass('cur-anchor');
            $($('#directory a')[navs.length - 1]).parent(".nodes").siblings().removeClass('cur-anchor');
        }
    }

    // 字体分辨率 - start
    function resi() {
        var html = document.querySelector("html");
        var wW = document.body.clientWidth || document.documentElement.clientWidth;
        var maxW = 750;
        var minW = 320;
        if (wW > maxW) wW = maxW;
        var ratio = wW / maxW;
        // 45.0667px
        html.style.fontSize =100 * ratio + "px"
    }
    window.addEventListener("DOMContentLoaded", function() {
        var bodys = document.querySelector("body").style;
        bodys.opacity = "1";
        bodys.filter = "alpha(opacity=100)";
        resi()
    });
    window.addEventListener('resize', resi)
    // 字体分辨率 - end

    $('.cover-content').remove()
    </script>

    <script>
        function click_follow(writer_id) {
            if (uid == 0){
                $('.drawer, .login-main').attr('style','display: block;');
                return ;
            }
            $.ajax({
                type: 'POST',
                url: "http://www.cocoachina.com/articles/click_follow",
                data: {
                    writer_id: writer_id
                },
                headers: {
                    'X-CSRF-TOKEN': 'UHTlF87GUSX7Fc2i8l34xlCwzyt0c5HisHVRSaoi'
                },
                dataType: "json",
                success: function (res) {
                    if(-1 == res.code){
                        alert(res.msg);
                    }else{
                        alert(res.msg);
                        location.reload();
                    }
                }
            })
        }
        //微信分享
        var article_info = JSON.parse(localStorage.getItem('article_info'))

        with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')). src='http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
        
        window._bd_share_config = {
            common : {
                bdText : $('.cocoa-article-title').html() + '-CocoaChina',	
                bdComment : $('#details').text().substring(0, 200).trim(),
                bdUrl : window.location.href, 	
                bdPic : $("#details img").eq(0).attr('src')?$("#details img").eq(0).attr('src'):'https://jdi.cocosbcx.net/image/cocoachina/bg.png'
            },
            share : [{
                "bdSize" : 16,
                 bdStyle: 0,
            }],
            image : [{
                viewType : 'list',
                viewPos : 'top',
                viewColor : 'black',
                viewSize : '16',
                viewList : ['weixin', 'qzone','tsina','huaban','tqq','renren']
            }],
            selectShare : [{
            	"bdselectMiniList" : ['qzone','tqq','kaixin001','bdxc','tqf']
            }]
        }
        console.log(  window._bd_share_config );
        

        $('.concat').remove();
        $('.cover-content').remove()
    </script>
  
</body>

</html>
